package com.ruoyi.web.controller.h5.login;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.H5LoginBody;
import com.ruoyi.common.core.domain.model.H5RegisterBody;
import com.ruoyi.common.core.domain.model.H5ForgotPasswordBody;
import com.ruoyi.common.core.domain.model.H5SendSmsCodeBody;
import com.ruoyi.system.sms.SmsCodeService;
import com.ruoyi.framework.web.service.app.H5LoginService;
import com.ruoyi.framework.web.service.app.H5RegisterService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * H5端用户登录控制器
 * 处理H5用户的登录、注册、退出等请求
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/h5")
@Api(tags = "H5端用户认证接口")
public class H5LoginController extends BaseController {

    @Autowired
    private H5LoginService h5LoginService;

    @Resource
    private H5RegisterService h5RegisterService;

    @Autowired
    private SmsCodeService smsCodeService;

    /**
     * H5用户登录
     * 基于手机号/用户名+密码登录，返回JWT令牌
     */
    @PostMapping("/login")
    @ApiOperation("H5用户登录")
    public AjaxResult login(@RequestBody H5LoginBody loginBody) {
        // 调用登录服务处理认证逻辑
        String token = h5LoginService.login(loginBody);
        // 返回令牌（前端需存储token用于后续请求）
        return AjaxResult.success().put("token", token);
    }

    /**
     * H5用户注册
     * 支持手机号注册，需验证验证码
     */
    @PostMapping("/register")
    @ApiOperation("H5用户注册")
    public AjaxResult register(@RequestBody H5RegisterBody registerBody) {
        // 调用注册服务处理用户创建逻辑
        h5RegisterService.register(registerBody);
        return AjaxResult.success("注册成功，请登录");
    }

    /**
     * H5用户退出登录
     * 清除当前用户的token缓存
     */
    @PostMapping("/logout")
    @ApiOperation("H5用户退出")
    @PreAuthorize("@userType.isH5()")
    public AjaxResult logout(HttpServletRequest request, HttpServletResponse response) {
        // 调用退出服务处理token失效逻辑
        h5LoginService.logout(request, response);
        return AjaxResult.success("退出成功");
    }

    /**
     * 获取当前登录H5用户信息
     * 需携带有效token，用于前端展示用户信息
     */
    @GetMapping("/getInfo")
    @ApiOperation("获取当前H5用户信息")
//    @PreAuthorize("@userType.isH5()")
    public AjaxResult getLoginUserInfo() {
        // 从Security上下文获取当前登录用户信息
        return AjaxResult.success(h5LoginService.getLoginUserInfo());
    }

    /**
     * 发送短信验证码
     * 支持注册、登录和忘记密码场景
     */
    @PostMapping("/sendSmsCode")
    @ApiOperation("发送短信验证码")
    public AjaxResult sendSmsCode(@RequestBody H5SendSmsCodeBody sendSmsCodeBody) {
        try {
            // 忘记密码场景需要检查用户是否存在
            if ("forgot_password".equals(sendSmsCodeBody.getScene())) {
                if (!h5LoginService.checkUserExistsByPhone(sendSmsCodeBody.getPhoneNumber())) {
                    return AjaxResult.error("该手机号未注册，请先注册");
                }
            }
            
            boolean result = smsCodeService.sendSmsCode(sendSmsCodeBody.getPhoneNumber(), sendSmsCodeBody.getScene());
            if (result) {
                return AjaxResult.success("短信验证码发送成功");
            } else {
                return AjaxResult.error("短信验证码发送失败");
            }
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 忘记密码重置
     * 通过手机号验证码重置密码
     */
    @PostMapping("/forgotPassword")
    @ApiOperation("忘记密码重置")
    public AjaxResult forgotPassword(@RequestBody H5ForgotPasswordBody forgotPasswordBody) {
        try {
            // 调用忘记密码服务
            h5LoginService.forgotPassword(
                forgotPasswordBody.getPhoneNumber(),
                forgotPasswordBody.getSmsCode(),
                forgotPasswordBody.getNewPassword(),
                forgotPasswordBody.getConfirmPassword()
            );
            return AjaxResult.success("密码重置成功，请使用新密码登录");
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
}